package com.zhs.gccs.base;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.Environment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.iflytek.cloud.SpeechUtility;
import com.liulishuo.filedownloader.FileDownloader;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.zhs.gccs.dao.converter.ImageBeanConverter;
import com.zhs.gccs.dao.converter.ImageDataConverter;
import com.zhs.gccs.dao.converter.LocationBeanConverter;
import com.zhs.gccs.dao.converter.ProjectConverter;
import com.zhs.gccs.dao.converter.UserConverter;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.model.ImageBean;
import com.zhs.gccs.model.LocationBean;
import com.zhs.gccs.model.MissionBean;
import com.zhs.gccs.model.TaskFeedback;
import com.zhs.gccs.model.TaskProject;
import com.zhs.gccs.model.User;
import com.zhs.gccs.utils.PermissionUtils;
import com.zhs.gccs.utils.ToastUtils;

import org.xutils.db.converter.ColumnConverterFactory;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class App extends Application {
    private static Application sApplication;
//    public static LocationService locationService;
//    private static List<GjData> gjData;//轨迹点
//    private static SmTask mTask;


    @Override
    public void onCreate() {
        super.onCreate();
//        initLocation();
        initLog();
        initXutils();
        ToastUtils.init(this);
        PermissionUtils.init(this);
        FileDownloader.setupOnApplicationOnCreate(this);
        // 将“12345678”替换成您申请的APPID，申请地址：http://www.xfyun.cn
        // 请勿在“=”与appid之间添加任何空字符或者转义符
        // 注意： appid 必须和下载的SDK保持一致，否则会出现10407错误
        SpeechUtility.createUtility(App.this, "appid=903266c6");

        //umeng
        /**
         * 注意: 即使您已经在AndroidManifest.xml中配置过appkey和channel值，也需要在App代码中调
         * 用初始化接口（如需要使用AndroidManifest.xml中配置好的appkey和channel值，
         * UMConfigure.init调用中appkey和channel参数请置为null）。
         */
        UMConfigure.init(this, "66a35bc5cac2a664de78ea55", "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
//            // 选用AUTO页面采集模式
//            MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        // 选用LEGACY_AUTO页面采集模式  umeng 默认模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.LEGACY_AUTO);
        // 支持在子进程中统计自定义事件
        UMConfigure.setProcessEvent(true);
        MobclickAgent.setDebugMode(true);
    }


    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }
    //    onConfigurationChanged( ) ：在配置被改变时触发 。
//    onCreate() ：在程序创建时创建。
//    onLowMemory() ：内存不够时触发。
//    onTerminate() ：当终止程序时调用 但是不能保证一定调用
//    onTrimMemory() ：在内存清理时触发

//    private void initLocation() {
//        LocationClient.setAgreePrivacy(true);
//        locationService = new LocationService(getApplicationContext());
////        mVibrator = (Vibrator) getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
//        SDKInitializer.initialize(getApplicationContext());
//        SDKInitializer.setCoordType(CoordType.GCJ02);
//    }

    public static Application getApplication() {
        if (sApplication == null) {
            try {
                //通过反射获取Application
                @SuppressLint({"DiscouragedPrivateApi", "PrivateApi"})
                Method method = Class.forName("android.app.ActivityThread").
                        getDeclaredMethod("currentApplication");
                sApplication = (Application) method.invoke(null, new Object[]{});
            } catch (NoSuchMethodException | ClassNotFoundException | IllegalAccessException |
                     InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return sApplication;
    }

    private void initXutils() {
        x.Ext.init(this);
        x.Ext.setDebug(false); //输出debug日志，开启会影响性能
        ColumnConverterFactory.registerColumnConverter(User.class, new UserConverter());

        ColumnConverterFactory.registerColumnConverter(TaskFeedback.class, new ImageDataConverter());

        ColumnConverterFactory.registerColumnConverter(ImageBean.class, new ImageBeanConverter());
//        ColumnConverterFactory.registerColumnConverter(ArrayList.class,new ListImageBeanConverter());

        ColumnConverterFactory.registerColumnConverter(TaskProject.class, new ProjectConverter());

        ColumnConverterFactory.registerColumnConverter(LocationBean.class, new LocationBeanConverter());

    }

    private void initLog() {
        //默认full,正式版本时使用none
        Logger.init(DbConstants.TAG)
                .logLevel(LogLevel.FULL);
    }


    /**
     * 解析地址数据
     */
    public static MissionBean getTaskBean(String pPath, String pFileName) {
        String pjson = null;
        // String content = parseFile(pAll);
        //或得sd的路径
        //获取状态
        String state = Environment.getExternalStorageState();
        //挂在状态
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            //或得要解析的文件
            File file = new File(pPath, pFileName);
            //使用流读取
            try {
                FileInputStream fis = new FileInputStream(file);
                //得到文件的大小
                int size = fis.available();
                byte[] buffer = new byte[size];
                //读取文件
                fis.read(buffer);
                pjson = new String(buffer);
                fis.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return JSON.parseObject(pjson, new TypeReference<MissionBean>() {
        });
    }
}
